package com.dman.multi.cmd;

import org.apache.pivot.collections.List;
import org.apache.pivot.util.Vote;
import org.apache.pivot.wtk.Alert;
import org.apache.pivot.wtk.Alert.OptionSequence;
import org.apache.pivot.wtk.Dialog;
import org.apache.pivot.wtk.DialogStateListener;
import org.apache.pivot.wtk.MessageType;
import org.apache.pivot.wtk.Prompt;

import com.dman.multi.core.Download;
import com.dman.multi.ui.DMan;

public class GUIPauseCommand implements Command {
	
	private DMan parent;
	private List<Download> downloadList;

	public GUIPauseCommand(DMan parent, List<Download> downloadList) {
		super();
		this.parent = parent;
		this.downloadList = downloadList;
	}

	@Override
	public void execute() {
		int index = parent.getSelectedTableViewIndex();
		if(index >= 0){
			final Download d = downloadList.get(index);
			try {
				if(!d.isResumeSupported()){
					final Alert alert = new Alert();
					alert.setMessageType(MessageType.QUESTION);
					alert.setMessage("This download cannot be resumed, are you sure you want to stop it?");
					OptionSequence os = alert.getOptions();
					os.remove(0, os.getLength());
					os.add("Yes");
					os.add("No");
					alert.getDialogStateListeners().add(new DialogStateListener.Adapter(){
						@Override
						public Vote previewDialogClose(Dialog dialog, boolean result) {
							int index = alert.getSelectedOptionIndex();
							if(index < 1){
								try {
									d.pause(true);
								} catch (Exception e) {
									Prompt.prompt("Exception while pausing download", parent);
								}
							}
							return Vote.APPROVE;
						}
					});
					alert.open(parent);
				}
				d.pause(true);
			} catch (Exception e) {
				Prompt.prompt("Unable to pause download", parent);
			}
		}
	}

}
